<template>
  <section class="add">
    <el-form ref="form" :model="form" label-width="100px" :rules="rules">
      <el-form-item label="试卷名称" prop="subject">
        <el-input v-model="form.subject" placeholder="请输入试卷名称"></el-input>
      </el-form-item>

      <el-form-item label="年度" prop="grade">
        <el-input v-model="form.grade" placeholder="如：2021、2022"></el-input>
      </el-form-item>

      <!-- 考试开始时间（含时分秒） -->
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          placeholder="选择考试开始时间"
          style="width: 100%"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="startPickerOptions"
        ></el-date-picker>
      </el-form-item>

      <!-- 持续时间 -->
      <el-form-item label="持续时间" prop="totalTime">
        <el-input v-model.number="form.totalTime" placeholder="单位：分钟">
          <template #append>分钟</template>
        </el-input>
      </el-form-item>

      <!-- 自动计算的结束时间 -->
      <el-form-item label="结束时间">
        <el-input
          v-model="computedEndTime"
          readonly
          placeholder="自动计算结束时间"
        ></el-input>
      </el-form-item>

      <el-form-item label="考试类型" prop="type">
        <el-input v-model="form.type" placeholder="如：模拟考试、开卷考试"></el-input>
      </el-form-item>

      <!-- 选择题库 -->
      <el-form-item label="选择题库" prop="bankSubject">
        <el-select v-model="form.bankSubject" placeholder="请选择题库" style="width: 100%">
          <el-option
            v-for="bank in bankList"
            :key="bank.bankId"
            :label="bank.subject"
            :value="bank.subject"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit" icon="el-icon-plus">立即创建</el-button>
        <el-button @click="cancel" icon="el-icon-refresh-left">取消</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>
export default {
  data() {
    return {
      form: {
        subject: null,
        grade: null,
        startTime: null,         // 开始时间（含时分秒）
        totalTime: null,
        totalScore: 100,
        type: null,
        paperId: null,
        examCode: null,
        bankSubject: null,
        // 后端可接收 endTime
      },
      bankList: [],
      rules: {
        subject: [{ required: true, message: '考试科目不能为空', trigger: 'blur' }],
        grade: [{ required: true, message: '年度不能为空', trigger: 'blur' }],
        startTime: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
        totalTime: [
          { required: true, message: '持续时间不能为空', trigger: 'blur' },
          { type: 'number', message: '持续时间必须是数字', trigger: 'blur' }
        ],
        type: [{ required: true, message: '考试类型不能为空', trigger: 'blur' }],
        bankSubject: [{ required: true, message: '请选择题库', trigger: 'change' }]
      },
      startPickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 可选今天及以后
        }
      }
    };
  },
  computed: {
    // 计算结束时间（只用于显示）
    computedEndTime() {
      if (!this.form.startTime || !this.form.totalTime) {
        return '';
      }
      const start = new Date(this.form.startTime);
      const end = new Date(start.getTime() + this.form.totalTime * 60 * 1000);
      return this.formatDateTime(end);
    }
  },
  created() {
    this.fetchBankList();
  },
  methods: {
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hour = date.getHours().toString().padStart(2, '0');
      const min = date.getMinutes().toString().padStart(2, '0');
      const sec = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${min}:${sec}`;
    },

    fetchBankList() {
      this.$axios.get('/api/banks')
        .then(res => {
          if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
            this.bankList = res.data.data;
          } else {
            this.$message.error(res.data.message || '获取题库列表失败');
          }
        })
        .catch(err => {
          console.error('获取题库列表失败:', err);
          this.$message.error('网络异常，无法加载题库');
        });
    },

    generateExamCode() {
      const now = new Date();
      const dateStr = now.getFullYear() +
        (now.getMonth() + 1).toString().padStart(2, '0') +
        now.getDate().toString().padStart(2, '0');
      const timeStr = now.getHours().toString().padStart(2, '0') +
        now.getMinutes().toString().padStart(2, '0') +
        now.getSeconds().toString().padStart(2, '0');
      return `EXAM_${dateStr}_${timeStr}`;
    },

    onSubmit() {
  this.$refs.form.validate(valid => {
    if (!valid) {
      this.$message.error('请填写完整信息');
      return;
    }

    // 1. 生成唯一考试编码（全局唯一）
    const examCode = this.generateExamCode();
    this.form.examCode = examCode;

    // ✅ 2. 使用 examCode 作为 paperId（不再查最大值 +1）
    this.form.paperId = examCode;

    // 3. 计算 endTime
    const startTime = new Date(this.form.startTime);
    const endTime = new Date(startTime.getTime() + this.form.totalTime * 60 * 1000);

    // 4. 构造提交数据
    const submitData = {
      ...this.form,
      startTime: this.form.startTime,
      endTime: this.formatDateTime(endTime)
    };

    console.log('提交考试数据 :>> ', submitData);

    // 5. 提交考试信息（包含 paperId = examCode）
    this.$axios.post('/api/exam', submitData)
      .then(res => {
        if (res.data && res.data.code === 200) {
          this.$message.success('考试创建成功，正在跳转至组卷页面...');

          // 6. 跳转到组卷页面，传递 examCode 作为 paperId
          this.$router.push({
            path: '/autoPaper',
            query: {
              examCode: examCode,
              subject: this.form.subject,
              grade: this.form.grade,
              paperId: examCode,           // ← 统一使用 examCode
              bankSubject: this.form.bankSubject
            }
          });
        } else {
          this.$message.error(res.data.message || '考试创建失败');
        }
      })
      .catch(err => {
        console.error('请求失败:', err);
        this.$message.error('网络异常或提交失败');
      });
  });
},

    cancel() {
      this.$refs.form.resetFields();
    }
  }
};
</script>

<style lang="less" scoped>
.add {
  padding: 20px 40px;
  max-width: 600px;
  margin: 0 auto;
}
</style>